package com.gobo.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gobo.eduservice.clients.AliyunVodClient;
import com.gobo.eduservice.pojo.EduVideo;
import com.gobo.eduservice.mapper.EduVideoMapper;
import com.gobo.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author gobo-generator
 * @since 2021-09-19
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    AliyunVodClient vodClient;

    @Override
    public boolean removeVideoAndSourceById(String videoId) {

        EduVideo eduVideo = baseMapper.selectById(videoId);
        String videoSourceId = eduVideo.getVideoSourceId();
        if(!StringUtils.isEmpty(videoSourceId)){
            vodClient.deleteVideo(videoSourceId);
        }
        int i = baseMapper.deleteById(videoId);
        return i==1;
    }

    @Override
    public boolean removeVideoAndSourceByCourseId(String courseId) {
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("video_source_id");
        queryWrapper.eq("course_id",courseId);
        List<EduVideo> eduVideos = baseMapper.selectList(queryWrapper);
        List<String> videoSources = new ArrayList<>();
        for (int i = 0; i < eduVideos.size(); i++) {
            String sourceId = eduVideos.get(i).getVideoSourceId();
            if (!StringUtils.isEmpty(sourceId)){
                videoSources.add(sourceId);
            }
        }
        if (videoSources.size()>=1){
            vodClient.deleteVideoList(videoSources);
        }
        QueryWrapper<EduVideo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("course_id",courseId);
        int i = baseMapper.delete(queryWrapper2);
        return i!=0;
    }
}
